package com.yq.tanhua.ui.detail

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Email
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.yq.tanhua.R
import com.yq.tanhua.net.vo.TodayBest
import com.yq.tanhua.ui.MovementItemView
import com.yq.tanhua.ui.friends.RequestDataStatus
import com.yq.tanhua.ui.views.LoadingFooter

/**
 * 用户详情界面
 */
class PersonalInfoFragment : Fragment() {

    private val personalInfoViewModel: PersonalInfoViewModel by viewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val todaybest = arguments?.getSerializable("todayBest") as TodayBest
        personalInfoViewModel.loadData(todaybest.id.toString())
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ) = ComposeView(inflater.context).apply {
        layoutParams =
            LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        setContent {
            ShowContent(viewModel = personalInfoViewModel)
        }
    }


    @OptIn(ExperimentalMaterial3Api::class)
    @Composable
    fun ShowContent(viewModel: PersonalInfoViewModel) {
        val state = viewModel.persionUIState.collectAsState()//用户详情
        val sendMsgSate = viewModel.sendMsgUIState.collectAsState()//发消息状态
        val movementState = viewModel.personMovementUiState.collectAsState()//用户动态
        var showQuestionDialog by remember {
            mutableStateOf(false)
        }

        var askQuestionContent = remember {
            mutableStateOf("")
        }

        Box {
            Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
                state.value.let {
                    when (it.loadingState) {

                        is CommonRequestState.Loading -> {
                            ShowTipInfo(msg = "数据加载中。。。")
                        }

                        is CommonRequestState.LoadFail -> {
                            ShowTipInfo(msg = "数据加载失败${it.loadingState.msg}")
                        }

                        else -> {
                            showPersionInfo(it.data!!)
                        }
                    }
                }

                movementState.value.let {
                    if (it.isNullOrEmpty()) {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth(1f)
                                .fillMaxHeight(1f),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = "暂无动态", modifier = Modifier
                                    .background(Color.Yellow)
                            )
                        }
                    } else {
                        it.forEach { item ->
                            MovementItemView(item)
                        }
                    }
                }
            }
            Row(
                modifier = Modifier
                    .align(Alignment.BottomCenter)
                    .padding(bottom = 30.dp)
                    .clip(RoundedCornerShape(20))
                    .background(Color(0xFFF37717))
                    .padding(10.dp)
                    .clickable {
                        showQuestionDialog = true
                    }
            ) {
                Icon(Icons.Filled.Email, contentDescription = "", tint = Color.White)
                Spacer(modifier = Modifier.width(3.dp))
                Text(text = "聊一下", style = TextStyle(color = Color.White))
            }

            if (showQuestionDialog) {
                Dialog(
                    onDismissRequest = { showQuestionDialog = false },
                    properties = DialogProperties(
                        dismissOnBackPress = false,
                        dismissOnClickOutside = false
                    )
                ) {
                    Column(
                        modifier = Modifier
                            .width(200.dp)
                            .background(Color.White)
                            .padding(20.dp),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Text(text = "问题：" + state.value.question)
                        Spacer(modifier = Modifier.height(10.dp))
                        TextField(value = askQuestionContent.value, onValueChange = {
                            askQuestionContent.value = it
                        })
                        Spacer(modifier = Modifier.height(10.dp))
                        Button(onClick = {
                            if (askQuestionContent.value.isEmpty()) {
                                ToastUtils.showShort("请输入评论内容")
                                return@Button
                            }
                            sendMsg(askQuestionContent)
                        }) {
                            sendMsgSate.value.loadingState.let {
                                when(it){
                                    is CommonRequestState.Loading->{
                                        Text(text = "消息发送中")
                                    }
                                    is CommonRequestState.LoadSuccess->{
                                        showQuestionDialog = false
                                    }

                                    is CommonRequestState.LoadFail ->{
                                        Text(text = "发送消息")
                                        ToastUtils.showShort(it.msg)
                                    }

                                    else ->{
                                        Text(text = "发送消息")
                                    }

                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private fun sendMsg(
        askQuestionContent: MutableState<String>
    ) {
        personalInfoViewModel.sendChatMsg(askQuestionContent.value)
    }


    @Composable
    fun showPersionInfo(todayBest: TodayBest) {
        Column {
            AsyncImage(
                model = todayBest.avatar,
                contentScale = ContentScale.FillWidth,
                modifier = Modifier.height(320.dp),
                contentDescription = "Translated description of what the image contains"
            )

            Spacer(modifier = Modifier.height(4.dp))
            Row(modifier = Modifier.padding(horizontal = 20.dp)) {
                Column {
                    Row {
                        Text(text = todayBest.nickname)
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(text = todayBest.age.toString())
                    }

                    Spacer(modifier = Modifier.height(4.dp))

                    Row {
                        todayBest.tags.forEachIndexed { index, s ->
                            Text(text = s)
                            if (index != todayBest.tags.size - 1) {
                                Text(text = "  |  ")
                            }
                        }

                    }
                }
                Text(
                    text = "缘分值\n${todayBest.fateValue}",
                    modifier = Modifier
                        .weight(1f),
                    textAlign = TextAlign.End,
                    fontWeight = FontWeight.Bold
                )
            }
            Spacer(modifier = Modifier.height(4.dp))

            Spacer(
                modifier = Modifier
                    .height(4.dp)
                    .fillMaxWidth(1f)
                    .background(Color.LightGray)
            )

        }
    }


    @Composable
    fun ShowTipInfo(msg: String) {
        Box(
            Modifier
                .fillMaxHeight(1f)
                .fillMaxWidth(1f),
            contentAlignment = Alignment.Center
        ) {
            Text(text = msg)
        }
    }


}